package com.cmfi.utils;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.Font;
import java.awt.Color;
import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

public class BarCodeGeneratorUtils {

	private static final Logger log = LoggerFactory.getLogger(QRCodeGeneratorUtils.class);
	
	/**
	 * Description 生成一维码，即条形码
	 * @param message 条形码携带的消息
	 * @param filePath 文件路径，需要携带文件名，文件可自动生成，如果有文件，
	 * 内容可以自动覆盖，如：C:\\Users\\Lenovo\\Desktop\\喻总\\ttt.PNG
	 */ 
	public static void generateBarcodeImage(String message, String filePath) {
		int width = 400;
		int height = 100;
		try {
			BitMatrix matrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE_128, width, height);
			Path path = Paths.get(filePath);
			MatrixToImageWriter.writeToPath(matrix, "PNG", path);
			addTextToImage(message,filePath);
		} catch (Exception e) {
			log.info("[BarCodeGeneratorUtils][generateBarcodeImage] e,", e);
		}
	}

	public static void addTextToImage(String text, String filePath) {
		try {
			BufferedImage originalImage = ImageIO.read(new File(filePath));
			BufferedImage modifiedImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight()+40,
					BufferedImage.TYPE_INT_ARGB);
			Graphics2D g2d = modifiedImage.createGraphics();
			// 绘制原始图片
			g2d.drawImage(originalImage, 0, 0, null);
			// 设置文字属性
			g2d.setFont(new Font("Arial", Font.BOLD, 20));
			g2d.setColor(Color.BLACK); // 文字颜色
			g2d.drawString(text, 50, originalImage.getHeight()+25); // 在指定位置绘制文本
			g2d.dispose(); // 关闭graphics
			// 保存新图片
			ImageIO.write(modifiedImage, "PNG", new File(filePath));
		} catch (IOException e) {
			log.info("[BarCodeGeneratorUtils][writeTextToImage] e,", e);
		}
	}

	public static void main(String[] args) {
		generateBarcodeImage("f432qrio4hqrkew3213qkrjewqrh", "C:\\Users\\Lenovo\\Desktop\\喻总\\test.PNG");
	}

}
